<template>
  <div>
    <el-form ref="myform" :model="formItem" :rules="rules" label-width="120px" size="mini">
      <el-form-item label="盘点状态" prop="dutyResultStatus">
        <el-select v-model="formItem.dutyResultStatus" clearable placeholder="请选择状态" style="width:100%">
          <el-option v-for="item in inventoryResultStatus" :key="item.code" :label="item.text" :value="item.code" />
        </el-select>
      </el-form-item>
      <el-form-item label="修改后部门" prop="updateOrgCode">
        <treeselect
          v-model="formItem.updateOrgCode"
          :multiple="false"
          :options="availableOganizations"
          placeholder="请选择部门"
          @select="selcetOrg"
          @input="deSelcetOrg"
        />
      </el-form-item>
      <el-form-item label="修改后使用人" prop="updateUserName">
        <el-input
          v-model="formItem.updateUserName"
          placeholder="请选择使用人"
          clearable
          @clear="clearUser"
          @focus="handleUserIconClick"
        >
          <!-- <i slot="suffix" class="el-input__icon el-icon-s-custom" @click="handleUserIconClick" /> -->
        </el-input>
      </el-form-item>
      <el-form-item label="修改后位置" prop="updateLocationCode">
        <treeselect v-model="formItem.updateLocationCode" :multiple="false" :flat="true" :options="availableLocations" />
      </el-form-item>
    </el-form>
    <SelectDialog v-if="userSelDialogFormVisible" title="选择使用人" :show="userSelDialogFormVisible" :append-to-body="true" @on-ok="selectUserOk" @on-cancel="selectUserCancel">
      <UsersPage ref="usersTable" :for-selection="true" :multiple-selected="true" :org-code="formItem.updateOrgCode" />
    </SelectDialog>
  </div>
</template>

<script>
import {
  update,
  detail,
  status
} from '@neu/dcam-ui/api/inventoryResult'
import UsersPage from '@neu/auth-ui/views/users/tables'
import SelectDialog from '@neu/biz-core/components/SelectDialog'
import { tree as locationTree } from '@neu/dcam-ui/api/location'
import { tree as organizationsTree } from '@neu/auth-ui/api/organization'

// 定义一个表单原始项
const formItem = {
  name: '',
  updateLocationCode: '',
  updateOrgCode: '',
  updateOrgName: '',
  updateUserName: '',
  updateUserId: null,
  dutyResultStatus: ''
}
export default {
  name: 'InventoryExecuteResultEditForm',
  components: {
    SelectDialog,
    UsersPage
  },
  props: {
    // 根据id可判断是新建还是更新
    id: {
      required: false,
      type: Number,
      default: -1
    }
  },
  data() {
    return {
      // 编辑的表单内容
      formItem: {
        ...formItem
      },
      // 表单验证规则
      rules: {
        dutyResultStatus: [{
          required: true,
          message: '盘点状态不能为空',
          trigger: 'blur'
        }]
      },
      // 盘点结果状态
      inventoryResultStatus: [],
      // 位置树
      availableLocations: [],
      // 组织树
      availableOganizations: [],
      /** 是否初始化 */
      isUpdateInit: true,
      // 用户弹窗
      userSelDialogFormVisible: false
    }
  },
  watch: {
    // 监控id的变化，初始化表单数据
    id: {
      handler(newVal, oldVal) {
        this.fetch()
      },
      immediate: true
    }
  },
  created() {
    // 获取盘点结果状态
    status().then(res => { this.inventoryResultStatus = res.data })
    // 位置树
    locationTree().then(response => { this.availableLocations = response.data })
    organizationsTree().then(response => { this.availableOganizations = [response.data] })
  },
  methods: {
    // 初始化表单数据
    fetch() {
      if (this.id !== -1) {
        detail(this.id).then(response => {
          this.isUpdateInit = false
          this.formItem = {
            ...response.data
          }
        })
      } else {
        this.formItem = {
          ...formItem
        }
      }
    },
    // 保存操作，返回promise，后续处理交由调用者处理
    save() {
      console.log(this.formItem)
      const updated = this.id !== -1
      return new Promise(resolve => {
        this.$refs.myform.validate((valid) => {
          if (valid) {
            if (updated) {
              resolve(update(this.id, this.formItem))
            }
          } else {
            resolve(false)
          }
        })
      })
    },
    reset() {
      this.$refs.myform.resetFields()
    },
    /** 选择用户按钮 */
    handleUserIconClick() {
      if (!this.formItem.updateOrgCode) {
        this.$message({
          type: 'warning',
          message: '请选择使用部门!'
        })
        return
      }
      this.userSelDialogFormVisible = true
    },
    /** 使用人选择ok */
    selectUserOk() {
      var users = this.$refs.usersTable.selections
      if (users.length > 1) {
        return this.$message({
          showClose: true,
          message: '只能选择一个使用人',
          type: 'error'
        })
      }
      if (users.length < 1) {
        this.formItem.updateUserId = null
        this.formItem.updateUserName = ''
      } else {
        this.formItem.updateUserId = users[0].id
        this.formItem.updateUserName = users[0].name ? users[0].name : users[0].username
      }
      this.userSelDialogFormVisible = false
    },
    /** 责任人选择取消 */
    selectUserCancel() {
      this.userSelDialogFormVisible = false
    },
    /** 清除人员 */
    clearUser() {
      this.formItem.updateUserName = ''
      this.formItem.updateUserId = null
    },
    // 选择组织机构
    selcetOrg(value) {
      this.formItem.updateOrgName = value.title
    },
    // 取消选择组织机构
    deSelcetOrg(value) {
      // if (!value) this.formItem.updateOrgName = ''
      if (this.isUpdateInit) {
        this.formItem.updateUserId = ''
        this.formItem.updateUserName = ''
      }
      this.isUpdateInit = true
      if (value === undefined) {
        this.formItem.updateOrgName = ''
      }
    }
  }
}
</script>
